package com.zd.service.comment.impl;

import com.zd.domain.Comment;
import com.zd.domain.Reply;
import com.zd.domain.User;
import com.zd.mapper.*;
import com.zd.service.comment.CommentService;
import com.zd.service.reply.ReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CommentServiceImpl implements CommentService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private PostImgsMapper postImgsMapper;

    @Autowired
    private PostLikeMapper postLikeMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ReplyMapper replyMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据postId查询所有评论
     * @param postId
     * @return
     */
    @Override
    public List<Comment> comments(Integer postId) {

        List<Comment> comments = commentMapper.comments(postId);

        if ((comments != null) && (comments.size() > 0)){

            //遍历comments
            for (Comment comment : comments) {
                //查询评论的所有回复
                List<Reply> replys = replyMapper.findReplys(comment.getCommentId());

                if ((replys != null) && (replys.size() > 0)){

                    //根据userId查询user的信息
                    for (Reply reply : replys) {

                        User user = userMapper.findByUserID(reply.getUserId());

                        //将user存入reply中
                        if (user != null){
                            reply.setUser(user);
                        }

                    }

                    //将replys存入comment中
                    comment.setReplies(replys);

                }

            }


        }

        return comments;


    }

    /**
     * 发表评论
     * @param comment
     * @return
     */
    @Override
    public int saveComment(Comment comment) {
        return commentMapper.saveComment(comment);
    }
}
